package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author Junchen_N1
 * @Date 2025/6/17 9:00
 * @ClassName AuthFilter
 * @Description TODO
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private IgnoreWhiteConfig ignoreWhiteConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取白名单
        List<String> whites = ignoreWhiteConfig.getWhites();
        //获取request请求方式
        ServerHttpRequest request = exchange.getRequest();
        //获取请求URI
        String path = request.getURI().getPath();
        //校验是否为白名单
        if (StringUtils.matches(path,whites)){
            //放行
            return chain.filter(exchange);
        }

        //获取token
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        //非空校验
        if (StringUtils.isBlank(token)){
            return GatewayUtils.errorResponse(exchange,"token不能为空");
        }

        //token合法性校验
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange,"token不能为空");
        }

        //有效欣校验
        String userKey = JwtUtils.getUserKey(token);
        if (Boolean.FALSE.equals(redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey))){
            return GatewayUtils.errorResponse(exchange,"token已过期");
        }else {
            //token续命
            redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY + userKey,30, TimeUnit.MINUTES);
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
